<template>
  <div class="panel statistics">
    <div class="panel-header">
      <span>环境监测数据分析</span>
      <div class="chart-buttons">
        <el-radio-group v-model="currentChart" size="small">
          <el-radio-button label="soilTemp">土壤温度</el-radio-button>
          <el-radio-button label="soilPh">土壤pH值</el-radio-button>
          <el-radio-button label="co2">CO2浓度</el-radio-button>
          <el-radio-button label="airHum">空气湿度</el-radio-button>
          <el-radio-button label="relHum">相对湿度</el-radio-button>
        </el-radio-group>
      </div>
    </div>
    <div class="chart-container" v-loading="loading">
      <div id="mainChart" class="chart"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import * as echarts from 'echarts'
import service from '@/utils/request'
import { ElMessage } from 'element-plus'

const currentChart = ref('soilTemp')
const chart = ref(null)
const loading = ref(false)
const timer = ref(null)

// 将options移到顶层作用域
const options = {
  soilTemp: {
    title: { text: '土壤温度变化趋势' },
    yAxis: { name: '温度(℃)' },
    series: [{
      name: '土壤温度',
      type: 'line',
      smooth: true,
      itemStyle: { color: '#67e0e3' }
    }]
  },
  soilPh: {
    title: { text: '土壤pH值分布' },
    yAxis: { name: 'pH值' },
    series: [{
      name: 'pH值',
      type: 'bar',
      itemStyle: { color: '#fac858' }
    }]
  },
  co2: {
    title: { text: 'CO2浓度变化' },
    yAxis: { name: 'CO2(ppm)' },
    series: [{
      name: 'CO2浓度',
      type: 'line',
      areaStyle: {},
      smooth: true,
      itemStyle: { color: '#91cc75' }
    }]
  },
  airHum: {
    title: { text: '空气湿度分布' },
    yAxis: { name: '湿度(%)' },
    series: [{
      name: '空气湿度',
      type: 'scatter',
      itemStyle: { color: '#ee6666' }
    }]
  },
  relHum: {
    title: { text: '相对湿度变化' },
    yAxis: { name: '相对湿度(%)' },
    series: [{
      name: '相对湿度',
      type: 'line',
      step: 'middle',
      itemStyle: { color: '#73c0de' }
    }]
  }
}

// 设备编号映射
const deviceMap = {
  soilTemp: '327061586065758015',
  soilPh: '327061586065758007',
  soilCo2: '327061586065758011',
  airHumidity: '327061586065758013',
  airRelativeHumidity: '327061586065758014'
}

// 修改数据映射关系
const dataTypeMap = {
  soilTemp: { device: 'soilTemp', unit: '℃' },
  soilPh: { device: 'soilPh', unit: '' },
  co2: { device: 'soilCo2', unit: 'ppm' },
  airHum: { device: 'airHumidity', unit: '%' },
  relHum: { device: 'airRelativeHumidity', unit: '%' }
}

// 监听图表切换
watch(currentChart, async (newType) => {
  try {
    loading.value = true
    // 直接获取当前类型的数据
    const currentData = await getCurrentData(newType)
    if (currentData) {
      updateChartWithData(newType, currentData)
    }
  } catch (error) {
    console.error('切换图表失败:', error)
    ElMessage.error('图表加载失败')
  } finally {
    loading.value = false
  }
})

// 获取当前类型的数据
const getCurrentData = async (type) => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')

  const endTime = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`
  const startTime = '2024-12-01T00:00:00'

  const deviceNumber = deviceMap[dataTypeMap[type].device]
  console.log('请求数据:', { type, deviceNumber, startTime, endTime })

  try {
    const response = await service.get(`/api/sensor-data/${deviceNumber}`, {
      params: { startTime, endTime }
    })
    console.log('获取到数据:', response)
    return response.data
  } catch (error) {
    console.error('获取数据失败:', error)
    return null
  }
}

// 使用数据更新图表
const updateChartWithData = (type, data) => {
  if (!chart.value || !data?.length) return

  const timeData = data.map(item => {
    const date = new Date(item.createTime)
    return `${date.getMonth() + 1}/${date.getDate()} ${date.getHours()}:${date.getMinutes()}`
  })

  const valueData = data.map(item => item.value)

  const option = {
    ...options[type],
    grid: {
      top: 60,
      right: 30,
      bottom: 40,
      left: 50,
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      },
      formatter: function(params) {
        const item = params[0]
        const unit = dataTypeMap[type].unit
        const value = item.value
        const time = item.name
        return `
          <div style="padding: 3px">
            <div style="margin-bottom: 3px">${time}</div>
            <div style="display: flex; align-items: center">
              <span style="display: inline-block; width: 10px; height: 10px; border-radius: 50%; background-color: ${item.color}; margin-right: 5px"></span>
              <span>${item.seriesName}：${value}${unit}</span>
            </div>
          </div>
        `
      },
      backgroundColor: 'rgba(0,47,167,0.7)',
      borderColor: 'rgba(0,183,255,0.7)',
      textStyle: {
        color: '#fff'
      }
    },
    xAxis: {
      type: 'category',
      data: timeData,
      axisLine: { lineStyle: { color: '#fff' } },
      axisLabel: {
        interval: 'auto',
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: options[type].yAxis.name,
      axisLine: { lineStyle: { color: '#fff' } },
      splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } }
    },
    series: [{
      ...options[type].series[0],
      data: valueData
    }]
  }

  chart.value.clear()
  chart.value.setOption(option, true)
}

// 初始化图表
const initChart = () => {
  if (!chart.value) {
    chart.value = echarts.init(document.getElementById('mainChart'))
    getCurrentData(currentChart.value).then(data => {
      if (data) {
        updateChartWithData(currentChart.value, data)
      }
    })
  }
}

onMounted(() => {
  initChart()
  timer.value = setInterval(async () => {
    const data = await getCurrentData(currentChart.value)
    if (data) {
      updateChartWithData(currentChart.value, data)
    }
  }, 60000)

  window.addEventListener('resize', () => chart.value?.resize())
})

onBeforeUnmount(() => {
  if (timer.value) {
    clearInterval(timer.value)
  }
  chart.value?.dispose()
  window.removeEventListener('resize', () => chart.value?.resize())
})
</script>

<style scoped>
.statistics {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.panel-header {
  padding: 0 10px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.chart-container {
  flex: 1;
  padding: 10px;
  min-height: 0;
}

.chart {
  width: 100%;
  height: 100%;
  background: rgba(0,47,167,0.1);
  border-radius: 4px;
}

:deep(.el-radio-button__inner) {
  background: transparent;
  border-color: rgba(0,183,255,0.2);
  color: #fff;
}

:deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
  background-color: rgba(0,183,255,0.2);
  border-color: #30f3f9;
  box-shadow: -1px 0 0 0 #30f3f9;
}
</style> 